package JavaFoundation.myLock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

//同步锁的演示。线程可以进入任何一个它已经拥有的锁所同步着的代码块。
/*
synchronized和ReentrantLock都是同步锁
 */
class Phone implements Runnable{
    public Phone(){}
    public synchronized void sendSMS()throws Exception{
        System.out.println(Thread.currentThread().getName()+"=======com in sendSMS");
        sendEmail();
    }
    public synchronized void sendEmail()throws Exception{
        System.out.println(Thread.currentThread().getName()+"=======com in sendEmail");
    }

    Lock lock = new ReentrantLock();
    @Override
    public void run() {
        get();
    }
    public void get(){
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName()+"=======com in get()");
            Set();
        }finally {
            lock.unlock();
        }
    }
    public void Set(){
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName()+"=======com in Set()");
        }finally {
            lock.unlock();
        }
    }


}

public class SynchronizationDemo {


    public static void main(String[] args) {
        Phone phone = new Phone();
        new Thread(()->{
            try {
                phone.sendSMS();
            } catch (Exception e) {
                e.printStackTrace();
            }
        },"AAA").start();

        new Thread(()->{
            try {
                phone.sendSMS();
            } catch (Exception e) {
                e.printStackTrace();
            }
        },"BBB").start();

        try { TimeUnit.SECONDS.sleep(1L); } catch (InterruptedException e) { e.printStackTrace(); }

        System.out.println();
        System.out.println();
        System.out.println();

        Thread thread1 = new Thread(phone,"aaa");
        Thread thread2 = new Thread(phone,"bbb");
        thread1.start();
        thread2.start();


    }
}
